import { Icon } from '@iconify/vue'
import {
  Button,
  Col,
  Form,
  FormItem,
  Input,
  InputNumber,
  Modal,
  RadioGroup,
  Row,
  Space,
  Spin,
  Tag,
  TreeSelect
} from 'ant-design-vue'
import { defineComponent, onMounted, ref } from 'vue'

import { dictApi } from '@/apis'
import { ProTable } from '@/components'
import { dictToOptions } from '@/utils'

import { cacheOptions, menuTypeOptions, visibleOptions } from './constants'
import { useMenuTree, useOperation, useTable, useToolbar } from './hooks'
import { MenuFormType } from './types'

export default defineComponent({
  name: 'MenuView',
  setup() {
    const statusOptions = ref([] as OptionItem[])
    const { tableConfig, tableRefHook } = useTable()
    const { getMenuTree, ...menuTreeRestHook } = useMenuTree()
    const operationHook = useOperation({
      getMenuTree,
      tableRefHook
    })
    const toolbarHook = useToolbar({
      getMenuTree,
      tableRefHook
    })

    async function init() {
      const [dictStatus] = await Promise.all([
        dictApi.getDictDataList('sys_normal_disable')
      ])

      statusOptions.value = dictToOptions(dictStatus)

      tableRefHook.updateFormItem({
        field: 'status',
        key: 'itemRender.props.options',
        value: statusOptions.value
      })
    }

    onMounted(() => {
      init()
    })

    return {
      statusOptions,
      tableRef: tableRefHook.tableRef,
      tableConfig,
      ...menuTreeRestHook,
      ...operationHook,
      ...toolbarHook
    }
  },
  render() {
    const renderForm = (type: MenuFormType) => {
      const formModel = type === 'add' ? this.addFormModel : this.editFormModel
      const formRef = type === 'edit' ? this.addFormRef : this.editFormRef

      const FormItemIcon = () => (
        <Col span={24}>
          <FormItem label={'菜单图标'}>
            <Input
              v-model:value={formModel.icon}
              v-slots={{
                suffix: () => (
                  <Button
                    type={'link'}
                    size={'small'}
                    href="https://icon-sets.iconify.design/"
                    target="_blank"
                  >
                    从网站选取
                  </Button>
                )
              }}
            />
          </FormItem>
        </Col>
      )
      const FormItemPath = () => (
        <Col span={12}>
          <FormItem label={'路由地址'} {...formRef.validateInfos['path']}>
            <Input v-model:value={formModel.path} />
          </FormItem>
        </Col>
      )
      const FormItemComponent = () => (
        <Col span={12}>
          <FormItem label={'组件路径'}>
            <Input v-model:value={formModel.component} />
          </FormItem>
        </Col>
      )
      const FormItemRedirect = () => (
        <Col span={12}>
          <FormItem label={'跳转地址'}>
            <Input v-model:value={formModel.redirect} />
          </FormItem>
        </Col>
      )
      const FormItemVisible = () => (
        <Col span={12}>
          <FormItem label={'显示状态'}>
            <RadioGroup
              v-model:value={formModel.visible}
              options={visibleOptions}
            />
          </FormItem>
        </Col>
      )
      const FormItemCache = () => (
        <Col span={12}>
          <FormItem label={'是否缓存'}>
            <RadioGroup
              v-model:value={formModel.isCache}
              options={cacheOptions}
            />
          </FormItem>
        </Col>
      )
      const FormItemStatus = () => (
        <Col span={12}>
          <FormItem label={'菜单状态'}>
            <RadioGroup
              v-model:value={formModel.status}
              options={this.statusOptions}
            />
          </FormItem>
        </Col>
      )
      const FormItemPerms = () => (
        <Col span={12}>
          <FormItem label={'权限字符'}>
            <Input v-model:value={formModel.perms} />
          </FormItem>
        </Col>
      )

      const formMap = {
        M: () => (
          <>
            <Row gutter={15}>
              <FormItemIcon />
            </Row>
            <Row gutter={15}>
              <FormItemPath />
              <FormItemStatus />
            </Row>
            <Row gutter={15}>
              <FormItemVisible />
            </Row>
          </>
        ),
        C: () => (
          <>
            <Row gutter={15}>
              <FormItemIcon />
            </Row>
            <Row gutter={15}>
              <FormItemPath />
              <FormItemComponent />
            </Row>
            <Row gutter={15}>
              <FormItemRedirect />
              <FormItemPerms />
            </Row>
            <Row gutter={15}>
              <FormItemVisible />
              <FormItemStatus />
            </Row>
            <Row gutter={15}>
              <FormItemCache />
            </Row>
          </>
        ),
        F: () => (
          <>
            <Row gutter={15}>
              <FormItemPerms />
            </Row>
          </>
        )
      }

      return (
        <Modal
          title={type === 'add' ? '添加菜单' : '修改菜单'}
          visible={type === 'add' ? this.showAdd : this.showEdit}
          confirmLoading={type === 'add' ? this.addLoading : this.editLoading}
          width={680}
          onOk={type === 'add' ? this.handleAdd : this.handleEdit}
          onCancel={type === 'add' ? this.handleCloseAdd : this.handleCloseEdit}
          destroyOnClose
        >
          <Spin spinning={this.treeLoading}>
            <Form
              labelCol={{
                style: {
                  width: '100px'
                }
              }}
            >
              <FormItem label={'上级菜单'}>
                <TreeSelect
                  v-model:value={formModel.parentId}
                  v-slots={{
                    title: ({ title, children }) => {
                      return (
                        <>
                          <span>{title}</span>
                          {children?.length ? (
                            <span style={{ color: '#999' }}>
                              ({children.length})
                            </span>
                          ) : null}
                        </>
                      )
                    }
                  }}
                  treeData={this.menuTree}
                  fieldNames={{
                    children: 'children',
                    label: 'title',
                    value: 'key'
                  }}
                  allowClear
                  placeholder={'请选择上级菜单'}
                />
              </FormItem>
              <FormItem label={'菜单类型'}>
                <RadioGroup
                  v-model:value={formModel.menuType}
                  options={menuTypeOptions}
                />
              </FormItem>
              <Row gutter={15}>
                <Col span={12}>
                  <FormItem
                    label={'菜单名称'}
                    {...formRef.validateInfos['menuName']}
                  >
                    <Input v-model:value={formModel.menuName} />
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label={'显示顺序'}
                    {...formRef.validateInfos['orderNum']}
                  >
                    <InputNumber v-model:value={formModel.orderNum} min={0} />
                  </FormItem>
                </Col>
              </Row>
              {formMap[formModel.menuType]()}
            </Form>
          </Spin>
        </Modal>
      )
    }

    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            toolbar_buttons: () => (
              <Space>
                <Button
                  v-permission="system:menu:add"
                  type={'primary'}
                  ghost
                  onClick={() => this.handleShowAdd()}
                >
                  新增
                </Button>
                <Button onClick={this.handleToggleExpand}>展开/折叠</Button>
              </Space>
            ),
            icon: ({ row }) => {
              if (row.icon) {
                return <Icon icon={row.icon} inline />
              }
              return ''
            },
            status: ({ row }) =>
              row.status === '1' ? (
                <Tag color={'red'}>停用</Tag>
              ) : (
                <Tag color={'blue'}>正常</Tag>
              ),
            operation: ({ row }) => (
              <Space size={'small'}>
                <Button
                  v-permission="system:menu:edit"
                  type={'link'}
                  size={'small'}
                  onClick={() => this.handleShowEdit(row)}
                >
                  修改
                </Button>
                <Button
                  v-permission="system:menu:add"
                  type={'link'}
                  size={'small'}
                  disabled={row.visible === '1'}
                  onClick={() => this.handleShowAdd(row.menuId)}
                >
                  新增
                </Button>
                <Button
                  v-permission="system:menu:remove"
                  type={'link'}
                  size={'small'}
                  onClick={() => this.handleDelete(row)}
                >
                  删除
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        {/* 添加弹窗 */}
        {renderForm('add')}
        {/* 修改弹窗 */}
        {renderForm('edit')}
      </div>
    )
  }
})
